﻿using System;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace SqlSystemWatcher.Common
{
    public class ErrorLoggerCore
    {
        private readonly string _instanceName;
        private readonly string _messageText;

        public ErrorLoggerCore(string instanceName, string messageText)
        {
            _instanceName = instanceName;
            _messageText = messageText;
        }


        public void DoIt()
        {
            using (var backgroundWorker = new BackgroundWorker())
            {
                backgroundWorker.DoWork += BackgroundWorkerOnDoWork;
                backgroundWorker.RunWorkerAsync();
            }
        }

        private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                string conStr = ConfigurationManager.ConnectionStrings["ConStr"].ToString();

                using (var sqlConnection = new SqlConnection(conStr))
                {
                    var sqlDaSessionLog = new SqlDataAdapter
                        {
                            InsertCommand = new SqlCommand("[dbo].[ErrorDataLogInsert]")
                        };
                    sqlDaSessionLog.InsertCommand.Connection = sqlConnection;
                    sqlDaSessionLog.InsertCommand.Connection.Open();
                    sqlDaSessionLog.InsertCommand.CommandType = CommandType.StoredProcedure;
                    sqlDaSessionLog.InsertCommand.Parameters.AddWithValue("@InstanceName", _instanceName);
                    sqlDaSessionLog.InsertCommand.Parameters.AddWithValue("@MessageText", _messageText);
                    sqlDaSessionLog.InsertCommand.ExecuteNonQuery();
                    sqlDaSessionLog.InsertCommand.Connection.Close();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Not implemented");
            }
        }
    }
}